//周计划
Ext.namespace("MyPlan");

MyPlan.Weekly = function(p) {
	this.winPrev = p;
	this.winTasks = null;
	this.loadMask = null;
	this.winMsg=null;
	this.current=null;	
	thiz=this;
	this.txtItem = new Ext.form.TextField({
		fieldLabel: '任务名称',
		name:'itemTitle',
		allowBlank: false,
		width: 340
	});
	this.txtContent = new Ext.form.TextArea({
		fieldLabel: '内容描述',
		name:'itemContent',
		allowBlank: false,
		width: 570,
		height: 65
	});
	this.txtOther = new Ext.form.TextArea({
		fieldLabel: '重点、难点及需协调事宜',
		name:'itemOther',
		height: 40,
		width: 580
	});
	this.storeSource  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.TASKORIGINVALUE
    });
    this.storeType  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.PLANCATEGORY2
    });
    this.storeSend  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: [[0, '本周新增'],[1, '上周转入']]
    });
    this.renderSend = function(value){
		return OMS.PLAN_SEND[value];
	};
	this.renderSource = function(value){
		return OMS.TASKORIGIN[value];
	};
	this.renderStatus = function(value){
		return OMS.TASKSEXESTATUS[value];
	};	
	this.renderCategory = function(value){
		return OMS.PLANCATEGORY[value];
	};
	this.renderContent=function(value){
		return Ext.util.Format.ellipsis(value,22,'...');
	}
	this.cmbType = new Ext.form.ComboBox({
		width: 120,
		store: this.storeType,
		fieldLabel: '任务类别',
		name:'itemCategory',
        valueField: 'value',
        displayField: 'name',
        editable: false,
        allowBlank: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
	this.cmbSource = new Ext.form.ComboBox({
		width: 120,
		fieldLabel: '任务来源',
		name:'workSource',
		store: this.storeSource,
        valueField: 'value',
        displayField: 'name',
        allowBlank: false,
        value:'0',
        readOnly:true,
        mode: 'local'
	});
    this.dtPlanWork = new Ext.form.Hidden({name:'planWork'});
    this.dtPlanFinish = new Ext.form.DateField({
    	width: 120,
    	fieldLabel: '完成时间',
    	name:'planFinish',
		format: 'Y-m-d'
	});
	this.cmbSend = new Ext.form.ComboBox({
		width: 120,
		store: this.storeSend,
		fieldLabel: '任务性质',
		name:'sendFlag',
		value:'0',
        valueField: 'value',
        displayField: 'name',
        readOnly:true,
        editable: false,
        mode: 'local'
	});
    this.btnUpdate = new Ext.Button({
    	text: '修改',
		iconCls: 'icon-update',
		scope: this,
		handler: this.onUpdate
    });
    this.btnNew = new Ext.Button({
    	text: '添加',
    	iconCls: 'icon-new',
    	scope: this,
    	handler: this.onNew
    });
    this.btnAddTask = new Ext.Button({
    	text: '添加在执行中任务',
    	iconCls: 'icon-new',
    	scope: this,
    	handler: this.onAddTask
    });
    this.btnReset = new Ext.Button({
    	text: '修复',
    	iconCls: 'icon-reset',
    	scope: this,
    	handler: this.resetForm
    });
    this.btnRemove = new Ext.Button({
    	text: '删除',
    	iconCls: 'icon-remove',
    	scope: this,
    	handler: this.onRemove
    });
    
	this.form = new Ext.FormPanel({
		region: 'north',
        bodyStyle: 'padding: 5px 5px 0',
        height: 130,
        labelWidth: 70,
        labelAlign: 'right',
        items: [ { layout: 'column', border: false, defaults: {layout: 'form', border: false},
	        	items: [ { columnWidth: .33, items: [this.cmbSource] },
	        	         { columnWidth: .66, items: [this.txtItem]} ]
	    },{ layout: 'column', border: false, defaults: {layout: 'form', border: false},
	        	items: [ { columnWidth: .33, items: [this.cmbType]},
	        	         { columnWidth: .33, items: [this.cmbSend]},
     	            	 { columnWidth: .33, items: [this.dtPlanFinish] } ]
	    },    this.txtContent,this.dtPlanWork, 
	    	new Ext.form.Hidden({name:'itemId'}),
	    	new Ext.form.Hidden({name:'taskStatus'}),
	    	new Ext.form.Hidden({name:'taskId'})]
    });
	
	this.storeItems = new Ext.data.JsonStore({
	    url: Utils.formatURL('../myplan/listItems.form?&timesnap=' + Date.parse(new Date())),
	    root: 'result',
	    fields: ['itemId','taskId','taskStatus','itemCategory','itemTitle','itemOther','itemNation','workSource','itemContent','planWork','planFinish','sendFlag','itemFm']
	});
	
	this.column = [
		  {header: '明细编号',  align: 'center', width: 20,hidden:true, dataIndex: 'itemId'},
		  {header: '任务编号',  align: 'center', width: 20,hidden:true, dataIndex: 'taskId'}, 
		  {header: '任务明细编号',  align: 'center', width: 20,hidden:true, dataIndex: 'itemFm'},	        
 	      {header: '任务来源',  align: 'center', width: 25, dataIndex: 'workSource',renderer:this.renderSource},
 	      {header: '任务名称',  align: 'left', width: 50,dataIndex: 'itemTitle'}, 	 
 	      {header: '任务类别',  align: 'center', width: 25, dataIndex: 'itemCategory',renderer:this.renderCategory},       
 	      {header: '内容描述',  align: 'left', dataIndex: 'itemContent',renderer:this.renderContent},
 	      {header: '重点、难点及需协调事宜', width: 40, hidden:true,align: 'left', dataIndex: 'itemOther'},
 	      {header: '开始时间',  align: 'center', width: 35,hidden:true, dataIndex: 'planWork'},
 	      {header: '完成时间',  align: 'center', width: 30,dataIndex: 'planFinish'},
 	      {header: '任务性质',  align: 'center', width: 25,dataIndex: 'sendFlag',renderer:this.renderSend},
 	      {header: '任务状态',  align: 'center', width: 25,hidden:true,dataIndex: 'taskStatus',renderer:this.renderStatus}
 	];
	
	this.grid = new Ext.grid.GridPanel({
		store: this.storeItems,
        region: 'center',
        tbar: {items: [this.btnUpdate, this.btnNew, this.btnReset,this.btnAddTask, this.btnRemove]},
        cm: new Ext.grid.ColumnModel(this.column),
        sm: new Ext.grid.RowSelectionModel({singleSelect:false}),
        viewConfig: { forceFit: true },
        scope:this,
        listeners:{
      		  rowdblclick : function( g, index,e){      		  	
    			var rec = g.store.getAt(index);
    			this.scope.form.getForm().loadRecord(rec);
    			this.scope.current=rec;
			}
       }
	});
	
	MyPlan.Weekly.superclass.constructor.call(this, {
		layout: 'border',
		title: '计划子项',
        width: 700,
        height: 420,
        resizable: false,
        modal: true,
        autoScroll: true,
        closeAction: 'hide',
        items: [this.form, this.grid],
		buttons:[{
			text: '上一步',
			cls: 'x-btn-text-icon btn-prev',
			handler: this.onPrev,
			scope: this
		}, {
            text: '保存草稿箱',
            cls: 'x-btn-text-icon btn-save',
            handler: this.onSavePlan,
            scope: this
        }, {
            text: '保存并上报',
            cls: 'x-btn-text-icon btn-save',
            handler: this.onSubmitPlan,
            scope: this
        }, {
            text: '关闭',
            cls: 'x-btn-text-icon btn-cancel',
            handler: this.hide.createDelegate(this, [])
        }]
    });
};
Ext.extend(MyPlan.Weekly, Ext.Window,{
	resetForm:function(){
		this.form.getForm().reset();
		this.cmbSend.setValue('0');
		this.dtPlanWork.setValue(this.winPrev.startDate.getValue());
		this.dtPlanFinish.setValue(this.winPrev.endDate.getValue());
	},
	initWin:function(data){
		this.resetForm();
		if(data){
			this.grid.store.load({
				params:{planId:data.planId}
			});
		}else{
			this.grid.store.removeAll();
		}			
	},	
	onAddTask: function(btn, event) {
		if (this.winTasks == null) {
			this.winTasks = new MyPlan.AddTask(this);
		}
		this.winTasks.initWin();
		this.winTasks.show();
	},
	onNew: function(btn, event) {
		if (!this.form.getForm().isValid()){
			Utils.warn2('请输入相关信息再添加！',200);
			return;
		}
		var data=this.form.getForm().getFieldValues();
		if(this.checkDate(data,this.winPrev))
			return;
		this.resetForm();
		Utils.formatDate(data,'planWork');
		Utils.formatDate(data,'planFinish');	
		var rec = new this.grid.store.recordType(data);
        this.grid.store.insert(0, rec);
	},
	checkDate:function(data,pwin){
		/*if(data['planWork']>data['planFinish']){
			Utils.warn2('计划实施时间不应大于计划完成时间！',180);
			return true;
		}else if(data['planWork']<pwin.startDate.getValue()){
			Utils.warn2('计划实施时间不应小于计划周期开始时间！',180);
			return true;
		}else */if(data['planFinish']>pwin.endDate.getValue()){
			Utils.warn2('计划完成时间不应大于计划周期截至时间！',180);
			return true;
		}
		return false;
	},
	onRemove:function(btn,event){		
		var record = this.grid.getSelectionModel().getSelected();
		if(!record){
			Utils.warn2('请选择一条记录！',180);
			return false;
		}
        scope=this;      
        Utils.confirm2({msg:"删除后将不可恢复，您确实要删除吗？",
        	width:220,
        	fn:function(){
		        	scope.storeItems.remove(record);
		       }
	    });
	},
	onUpdate: function(btn, event) {
		if(this.current==null){
			Utils.warn2('请选择一条记录！',180);
			return false;
		}		
		var data=this.form.getForm().getFieldValues();
		//对有任务ID不允许更新
		if(data['taskId']){
			Utils.warn2('有对应任务计划不允许修改！',180);
			this.current=null;
			this.resetForm();
			return;
		}
		if (!this.form.getForm().isValid()){
			Utils.warn2('请输入相关信息再更新！',180);
			return;
		}
		/*var record = this.grid.getSelectionModel().getSelected();
		if(!record){
			Utils.warn('请选择一条记录！');
			return false;
		}*/
		if(this.checkDate(data,this.winPrev))
			return;
		var record=this.current; 
		this.current=null;
		this.resetForm();
		Utils.formatDate(data,'planWork');
		Utils.formatDate(data,'planFinish');
		//alert(Ext.util.JSON.encode(data));
		for(var id in record.data){
			record.set([id],data[id]);
		}
	},
	/**
	 * 保存草稿
	 */
	onSavePlan: function(btn, event) {
		this.winPrev.txtState.setValue('0');
		if (this.storeItems.getCount()<1){
			Utils.warn2('请添加计划项再保存！',180);
			return;
		}
		//this.uploadFiles();
		this.savePlan(btn, event);
		
	},
	/**
	 * 保存并上报
	 */
	onSubmitPlan: function(btn, event) {
		this.winPrev.txtState.setValue('1');
		if (this.storeItems.getCount()<1){
			Utils.warn2('请添加计划项再上报！',180);
			return;
		}
		scope=this;
		if(this.winMsg==null)
			this.winMsg=new Message.Msg(function(){
				//alert(scope.winMsg.txtRemind);
				scope.winPrev.txtRemind.setValue(scope.winMsg.txtRemind);
				//alert(scope.winPrev.txtRemind.getValue());
				scope.savePlan();
			},'上报后就不可修改，你确实要上报吗？');
		this.winMsg.show();
	},
	//保存计划
	savePlan:function(){
		var url='../myplan/savePlan.form?timesnap=' + Date.parse(new Date());
		var param=this.winPrev.form.getForm().getFieldValues();
		Utils.formatDate(param,'startDate');
  		Utils.formatDate(param,'endDate');
  		//alert(Ext.util.JSON.encode(param));
		var count=this.storeItems.getCount();
		for(var i=0 ;i<count;i++){
			var data = this.storeItems.getAt(i).data;
			param['grid_'+i]=Ext.util.JSON.encode(data);
		};
  		/* var conn = new Ext.data.Connection({
  			url:url,
  			method:'post'
  		})
		Utils.request(conn,{
  			params:param,
  			scope:this,
  			success:function(data){  							
  				Utils.info2();
  				this.scope.hide();			
				this.scope.winPrev.winMain.store.reload();					
  			}
  		});*/
		scope=this;
		this.winPrev.fileForm.getForm().submit({
			waitTitle : '系统提示',
			waitMsg : '数据提交中，请稍候...',
			url : url,
			params:param,
			method : 'POST',			
			success : function(fp, o){
				Utils.info2();
  				scope.hide();			
				scope.winPrev.winMain.store.reload();
			},
			failure : function(fp, o){
				alert('error');
			}
		});
	},
	onPrev: function(btn, event) {
		this.hide();
		this.winPrev.show();
	}
});